﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace giaodien
{
    public partial class BatDau : Form
    {
        static string Ten;
        static string Ma;
        decimal TongTien = 0;
        DataTable dtSanPham = new DataTable();

        //Các control cần tạo động
        TextBox txtTen = new TextBox();
        TextBox txtMa = new TextBox();
        RadioButton radNam = new RadioButton();
        RadioButton radNu = new RadioButton();


        public BatDau()
        {
            InitializeComponent();
        }
        // Khai báo delegate lấy tên người đăng nhập

        public static void LayTen(string TenGui,string MaGui) {
            Ten = TenGui;
            Ma = MaGui;
        }

        ConnectData obj = new ConnectData();
        private void frmMain_Load(object sender, EventArgs e)
        {
            lblXinChao.Text = "Xin chào " + Ten;
            ThreadDangXuat = new Thread(new ThreadStart(MoLaiDN));
            DataTable dtLoai = obj.laydulieuBang("select * from loai");
            cmbLoai.DataSource = dtLoai;
            cmbLoai.ValueMember = "Maloai";
            cmbLoai.DisplayMember = "TenLoai";
            cmbLoai.SelectedIndex = 0;
            lblNgayHienHanh.Text = DateTime.Now.ToShortDateString();
        }




        // Các hoạt động

        //Đăng xuất
        static Thread ThreadDangXuat;
        private void btnDangXuat_Click(object sender, EventArgs e)
        {
            if (lvwSPChon.Items.Count > 0)
            {
                DialogResult dag = MessageBox.Show("Bạn có những sản phẩm chưa lưu hóa đơn\n Bạn có muốn lưu không", "Thông báo", MessageBoxButtons.YesNoCancel);
                if (dag == DialogResult.Yes)
                {
                    btnThanhToan_Click(null, null);
                }
                else
                {
                    if (dag == DialogResult.No)
                    {
                        this.Close();
                        ThreadDangXuat.Start();
                    }
                    else
                    {
                        return;
                    }
                }
            }
            else {
                this.Close();
                ThreadDangXuat.Start();
            }
           
        }
        static void MoLaiDN()
        {
            Application.Run(new DN());
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            btnDangXuat_Click(null,null);
        }
        
        private void btnMini_Click(object sender, EventArgs e)   
        {
            UI.Mini(this);
        }

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            UI.MouseDown(e);
        }

        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            UI.MouseUp();
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            UI.MouseMove(this, MousePosition.X, MousePosition.Y);
        }
        

        private void quảnLýNhânViênToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QLNhanVien frm = new QLNhanVien();
            frm.Show();
        }

        private void nậpHàngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QLNhapHang frm = new QLNhapHang();
            frm.Show();
        }

        private void thốngKêTồnKhoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ThongKeTonKho frm = new ThongKeTonKho();
            frm.ShowDialog();
        }

        private void thốngKêBánHàngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txttongtien frm = new txttongtien();
            frm.ShowDialog();
        }

        //Nút chức năng
        private void btnHuy_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem lit in lvwSPChon.Items)
            {
                if (lit.Selected == true)
                {
                    lvwSPChon.Items.Remove(lit);
                }
            }
            TinhTongTien();
        }

        private void btnHuyToanBo_Click(object sender, EventArgs e)
        {
            lvwSPChon.Items.Clear();
            lblTongTien.Text = "Tổng tiền:";
            TongTien = 0;
        }


        private void btnThanhToan_Click(object sender, EventArgs e)
        {
            int iFlag = 1;
            if (KiemTraForm() == true)
            {
                string MaHD = obj.TaoMaHoaDon();
                string query = "insert into HoaDon(mahd,NgayLapHD,tenkhachhang,manv,tongtien) ";
                query += "values('" + MaHD + "','" + System.DateTime.Now.ToShortDateString() + "','" +txtTenKhachHang.Text + "','" + Ma + "'," + TongTien.ToString() + ")";
                if (obj.ChayHam(query) > 0)
                {
                    foreach(ListViewItem lit in lvwSPChon.Items){
                        string query1="insert into CTHD(mahd,masp,soluongban,thanhtien) values('"+MaHD+"','"+lit.Text+"','"+lit.SubItems[2].Text+"',"+lit.SubItems[3].Text+")";
                        if (obj.ChayHam(query1) > 0) {
                            ListViewItem litTag = (ListViewItem)lit.Tag;
                            string query2 = "Update sanpham set soluongtk="+(int.Parse(litTag.SubItems[5].Text)-int.Parse(lit.SubItems[2].Text))+" where masp='"+lit.Text+"'";
                            if (obj.ChayHam(query2) <= 0) {
                                iFlag = 0;
                                break;
                            }
                        }
                    }
                    if (iFlag == 1) {
                        MessageBox.Show("Đã thêm hóa đơn", "Thông báo", MessageBoxButtons.OK);
                        frmMain_Load(null, null);
                        ResetForm();
                    }    
                }
                else
                {
                    MessageBox.Show("Thêm hóa đơn thất bại", "Thông báo", MessageBoxButtons.OK);
                }
            }
            else {
                MessageBox.Show("Mời nhập tất cả thông tin", "Thông báo", MessageBoxButtons.OK);
            }
        }

        private Boolean KiemTraForm() {
            if (txtTenKhachHang.Text != ""&&lvwSPChon.Items.Count>0) {
                return true;
            }
            return false;
        }

        private void cmbLoai_SelectedIndexChanged(object sender, EventArgs e)
        {
                
                dtSanPham= obj.laydulieuBang("select * from SanPham where maloai='"+cmbLoai.SelectedValue+"'");
                LoadListView(dtSanPham);
        }


        private void LoadListView(DataTable dt) {
            lvwSanPham.Items.Clear();
            foreach (DataRow drSanPham in dt.Rows)
            {
                ListViewItem litSanPham = new ListViewItem();
                litSanPham.Text = drSanPham["MaSp"].ToString();
                litSanPham.SubItems.Add(drSanPham["tensp"].ToString());
                if ((bool)drSanPham[3] == true)
                    litSanPham.SubItems.Add("Nam");
                else
                    litSanPham.SubItems.Add("Nữ");
                litSanPham.SubItems.Add(drSanPham["kichco"].ToString());
                litSanPham.SubItems.Add(drSanPham[7].ToString());
                litSanPham.SubItems.Add(drSanPham["soluongtk"].ToString());
                lvwSanPham.Items.Add(litSanPham);
            }
        }
        private void cmbLoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled=true;
        }

        private void txtSoLuong_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) == false && char.IsControl(e.KeyChar) == false)
            {
                e.Handled = true;
            }
        }

        private void lvwSanPham_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right) {
                txtSoLuong.Text = "1";
                foreach (ListViewItem lit in lvwSPChon.SelectedItems)
                {
                    lit.Selected = false;
                }
            }
        }

        private void lvwSPChon_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {
                ListViewItem lit = lvwSPChon.GetItemAt(e.X, e.Y);
                if (lit != null) {
                    txtSoLuong.Text = lit.SubItems[2].Text;  
                }
                foreach (ListViewItem lit1 in lvwSanPham.SelectedItems)
                {
                    lit1.Selected = false;
                }
            }
        }

        private void lvwSanPham_MouseUp(object sender, MouseEventArgs e)
        {
            txtSoLuong.Focus();
        }

        private void txtSoLuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                e.SuppressKeyPress = true;
                if(lvwSanPham.SelectedIndices.Count > 0)
                    ChonSanPham();
                if (lvwSPChon.SelectedIndices.Count > 0)
                    SuaSanPham();
            }
        }

        private void TinhTongTien() {
            if (lvwSPChon.Items.Count > 0)
            {
                TongTien = 0;
                foreach (ListViewItem lit in lvwSPChon.Items)
                {
                    ListViewItem litTag = (ListViewItem)lit.Tag;
                    int DonGia = int.Parse(litTag.SubItems[4].Text);
                    int SoLuong = int.Parse(lit.SubItems[2].Text);
                    string ThanhTien = (SoLuong * DonGia).ToString();
                    lit.SubItems[3].Text = (string.Format("{0:N}", ThanhTien));
                    TongTien += decimal.Parse(ThanhTien);
                    lblTongTien.Text = "Tổng tiền: " + string.Format("{0:N}", TongTien) + " VND";
                }
            }
            else {
                TongTien = 0;
                lblTongTien.Text = "Tổng tiền:";
            }
        }

        private void SuaSanPham() {
            foreach (ListViewItem lit in lvwSPChon.SelectedItems)
            {
                ListViewItem litTag = (ListViewItem)lit.Tag;
                if (lit.Selected == true && int.Parse(txtSoLuong.Text) <= int.Parse(litTag.SubItems[5].Text))
                {
                    lit.SubItems[2].Text = txtSoLuong.Text;
                }
                else {
                    MessageBox.Show("Số lượng phải nhỏ hơn" + lit.Tag.ToString(), "Thông báo", MessageBoxButtons.OK);
                }
            }
            TinhTongTien();
        }

        private void ChonSanPham(){
            foreach(ListViewItem lit in lvwSanPham.SelectedItems){
                if (lit.Selected == true && int.Parse(txtSoLuong.Text) <= int.Parse(lit.SubItems[5].Text))
                {
                    lvwSanPham.Items.Remove(lit);
                    ListViewItem litChon = new ListViewItem();
                    litChon.Text = lit.Text;
                    litChon.SubItems.Add(lit.SubItems[1]);
                    litChon.SubItems.Add(txtSoLuong.Text);
                    int DonGia = int.Parse(lit.SubItems[4].Text);
                    int SoLuong = int.Parse(txtSoLuong.Text);
                    string ThanhTien = (SoLuong * DonGia).ToString();
                    litChon.SubItems.Add(string.Format("{0:N}", ThanhTien));
                    litChon.Tag = lit;
                    lvwSPChon.Items.Add(litChon);
                    TongTien += decimal.Parse(ThanhTien);
                    lblTongTien.Text = "Tổng tiền: " + string.Format("{0:N}", TongTien) + " VND";
                }
                else {
                    MessageBox.Show("Số lượng phải nhỏ hơn"+lit.SubItems[5].Text,"Thông báo",MessageBoxButtons.OK);
                }
            }
        }

        private void ResetForm(){
            lvwSPChon.Items.Clear();
            txtTenKhachHang.Text="";
            txtSoLuong.Text="1";
            lblTongTien.Text = "Tổng tiền:";
        }

        private void cmbTimTheo_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            switch (cmbTimTheo.Text) {
                case "Tên": {
                    pnlTimTheo.Controls.Clear();
                    
                    txtTen.Width = 100;
                    txtTen.Height = 20;
                    txtTen.TextChanged += new System.EventHandler(TimTen);
                    pnlTimTheo.Controls.Add(txtTen);
                    break;
                }
                case "Mã": {
                    pnlTimTheo.Controls.Clear();
                    
                    txtMa.Width = 100;
                    txtMa.Height = 20;
                    txtMa.TextChanged += new System.EventHandler(TimMa);
                    pnlTimTheo.Controls.Add(txtMa);
                    break;
                }
                case "Giới Tính": {
                    pnlTimTheo.Controls.Clear();
                    radNam.Text = "Nam";
                    radNam.AutoSize = true;
                    radNam.Checked = true;
                    radNu.Text = "Nữ";
                    radNu.AutoSize = true;
                    radNam.CheckedChanged += new System.EventHandler(TimGioiTinh);
                    pnlTimTheo.Controls.Add(radNam);
                    pnlTimTheo.Controls.Add(radNu);
                    break;
                }
            }
        }

        private void TimTen(object sender, EventArgs e)
        {
            if (txtTen.Text != "")
            {
                dtSanPham = obj.laydulieuBang("SELECT * FROM SanPham where tensp like '%" + txtTen.Text + "%' and maloai='"+cmbLoai.SelectedValue.ToString()+"'");
                LoadListView(dtSanPham);
            }
        }

        private void TimMa(object sender, EventArgs e)
        {
            if (txtMa.Text != "")
            {
                dtSanPham = obj.laydulieuBang("SELECT * FROM SanPham where masp like '%" + txtMa.Text + "%' and maloai='" + cmbLoai.SelectedValue.ToString() + "'");
                LoadListView(dtSanPham);
            }
        }

        private void TimGioiTinh(object sender, EventArgs e)
        {
            dtSanPham = obj.laydulieuBang("SELECT * FROM SanPham where gioitinhsp="+radNam.Checked+" and maloai='"+cmbLoai.SelectedValue.ToString()+"'");
            LoadListView(dtSanPham);
        }
    }
}
